#include "qbinaryrpc_clientprivate.h"

using namespace qbinaryrpc;

Client::Client() : d(new Private()) {
  connect(d,
          SIGNAL(done(int, const QVariant &)),
          this,
          SIGNAL(done(int, const QVariant &)));
  connect(d,
          SIGNAL(fault(int, int, const QString &)),
          this,
          SIGNAL(fault(int, int, const QString &)));
}

Client::~Client() {
  delete d;
}

void Client::open(const QHostAddress &host, quint16 port) {
  if(d->socket.isOpen() == false) {
    d->socket.connectToHost(host, port);
  }
}

bool Client::isOpen() {
  return d->socket.isOpen();
}

void Client::close() {
  if(d->socket.isOpen()) {
    d->socket.close();
    d->socket.disconnectFromHost();
  }
}

int Client::request(const QString &method_name,
                    const QVariantList &parameters) {
  if(d->socket.state() != QTcpSocket::ConnectedState ||
     d->socket.isValid() == false) return -1;
  Request request(d->id, method_name, parameters);
  QByteArray massive(request.composeRequest());
  if(massive.isEmpty()) return -1;
  d->socket.flush();
  d->socket.write(massive);
  d->requests.push_back(d->id);
  return d->id++;
}
